package com.ppt.javappt.entity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ppt.javappt.HelloApplication;
import com.ppt.javappt.controller.HelloController;
import com.ppt.javappt.pojo.SlideData;
import com.ppt.javappt.pojo.SlideFactory;
import com.ppt.javappt.util.AlertUtil;
import com.ppt.javappt.util.FileUtil;
import com.ppt.javappt.util.StringUtil;
import com.ppt.javappt.util.SystemUtil;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import lombok.Data;
import lombok.Getter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author cys
 * 幻灯片类 包含  幻灯片、左边的导航、右边的展示
 */
@Data
public class SlideFile extends AnchorPane {

    @Getter
    private final String fileId;

    List<Slide> slideList;
    SlideStackPane slideStackPane;
    ThumbnailPane thumbnailPane;
    ChangeListener<Slide> changeListener;

    public SlideFile(){
        this.fileId = UUID.randomUUID().toString();
        slideList = new ArrayList<>();
        slideStackPane = new SlideStackPane();
        thumbnailPane = new ThumbnailPane();
        this.getChildren().add(slideStackPane);
        this.getChildren().add(thumbnailPane);
        AnchorPane.setTopAnchor(slideStackPane,10.0);
        AnchorPane.setLeftAnchor(slideStackPane,255.0);
        AnchorPane.setTopAnchor(thumbnailPane,0.0);
        AnchorPane.setLeftAnchor(thumbnailPane,0.0);
        addSelectListener();
    }
    // 实现功能
    // 点击左侧缩略图导航 右侧随之切换到顶层
    public void addSelectListener(){
        // 获取选择模型
        thumbnailPane.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        MultipleSelectionModel<Slide> selectionModel = thumbnailPane.getSelectionModel();
        changeListener = new ChangeListener<Slide>() {
            @Override
            public void changed(ObservableValue<? extends Slide> observableValue, Slide oldSlide, Slide newSlide) {
                if (newSlide != null) { // 排除未选中的情况（如点击空白处）
                    newSlide.toFront();
                    HelloController.curSlide = newSlide;
                }
            }
        };
        selectionModel.selectedItemProperty().addListener(changeListener);
    }

    public void setSlideList(List<Slide> slideList) {
        thumbnailPane.setSlideList(slideList);
        slideStackPane.setSlideList(slideList);
        slideList.get(0).toFront();
        this.slideList = slideList;
    }
    // 清空 并清楚监听器
    public void clear(){
        slideList.clear();
        thumbnailPane.setSlideList(slideList);
        slideStackPane.setSlideList(slideList);
    }
    // 删除幻灯片
    public void delSlide(){
        List<Slide> slides = thumbnailPane.getSelectionModel().getSelectedItems();
        if(slides.isEmpty()){
            AlertUtil.showAlert("警告","请先选择幻灯片页");
        }else{
            Alert alert = AlertUtil.showConfirmAlert("删除","确认删除吗");
            if(alert.getResult() == ButtonType.OK){
                slideList.removeAll(slides);
                thumbnailPane.setSlideList(slideList);
                slideStackPane.setSlideList(slideList);
            }
        }
    }
    // 导入文件
    public void loadFile(){
        File file = FileUtil.openFile(HelloApplication.MainWindow);
        if(file!=null){
            System.out.println(file.getAbsoluteFile());
            try {
                List<SlideData> slideDataList = FileUtil.readObjectFromFile(
                        file,
                        new TypeReference<List<SlideData>>() {}
                );
                List<Slide> slideList = new ArrayList<>();
                for(SlideData slideData:slideDataList){
                    Slide slide = SlideFactory.createSlide(slideData);
                    slideList.add(slide);
                }
                SlideFile slideFile = new SlideFile();
                slideFile.setSlideList(slideList);
                SystemUtil.getInstance().setCurSlideFile(slideFile);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    // 导出单页幻灯片
    public void outputSlide(){
        List<Slide> slides = thumbnailPane.getSelectionModel().getSelectedItems();
        if(slides.isEmpty()){
            AlertUtil.showAlert("警告","请先选择幻灯片页");
        }else{
            for(Slide slide:slides){
                slide.outputAsImage();
            }
        }
    }
    // 保存文件 javaPPT
    public void saveFile(){
        File file = FileUtil.saveFile(HelloApplication.MainWindow,"保存");
        if(file!=null){
            System.out.println(file.getAbsoluteFile());
            try {
               savePPT(file);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    // 保存为PPT
    public void savePPT(File file) throws Exception{
        List<SlideData> dataList = new ArrayList<>();
        List<Slide> slideList = SystemUtil.getInstance().getCurSlideFile().getSlideList();
        for(Slide slide:slideList){
            dataList.add(SlideFactory.createSlideData(slide));
        }
        FileUtil.writeObjectToFile(dataList,file);
    }
    // 保存为PDF
    public void savePDF(File file) throws Exception{
        PDDocument document = new PDDocument();
        for(Slide slide:slideList){
            BufferedImage bufferedImage = SwingFXUtils.fromFXImage(slide.getThumbnail(),null);
            PDPage page = new PDPage(new PDRectangle(800,600));
            document.addPage(page);
            PDPageContentStream contentStream = new PDPageContentStream(document,page);
            PDImageXObject pdfImage = LosslessFactory.createFromImage(document,bufferedImage);
            contentStream.drawImage(pdfImage,0,0,800,600);
            contentStream.close();
        }

        document.save(file);
    }
    // 另存为
    public void saveAsFile(){
        File file = FileUtil.saveFile(HelloApplication.MainWindow,"另存为");
        if(file!=null){
            System.out.println(file.getAbsoluteFile());
            // 获取文件名（含后缀）
            String fileName = file.getName();
            String extension = StringUtil.getFileExtension(fileName);
            try {
                if("jppt".equals(extension)){
                    savePPT(file);
                }else if("pdf".equals(extension)){
                    savePDF(file);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
    public void updateThumbnailPane(){
        for(Slide slide:slideList){
            slide.updateThumbnail();
        }
    }
}
